<?php
namespace Wechat\Controller;

use Think\Controller;

class ValidateController extends Controller
{
    private $WxObj;

    public function main()
    {
        //验证服务器
        $this->validate();

        $this->WxObj = $this->getWxObj();

        ResponseController::switchResponse($this->WxObj);
    }

    /**
     * 验证服务器
     */
    private function validate()
    {
        // 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
        $signature = $_GET["signature"];
        // 时间戳
        $timestamp = $_GET["timestamp"];
        // 随机数
        $nonce = $_GET["nonce"];
        $echostr = $_GET["echostr"];
        if (empty($signature) || empty($timestamp) || empty($nonce) || empty($echostr)) {
            return;
        }
        // 1）将token、timestamp、nonce三个参数进行字典序排序
        $tmpArr = array($nonce, C('token'), $timestamp);
        sort($tmpArr, SORT_STRING);

        // 2）将三个参数字符串拼接成一个字符串进行sha1加密
        $str = implode($tmpArr);
        $sign = sha1($str);
        // 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        if ($sign == $signature) {
            echo $echostr;
        }
    }

    /**
     * 获取用户消息对象
     */
    private function getWxObj()
    {
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        //extract post data
        if (!empty($postStr)) {

            libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            return $postObj;
        } else {
            echo "";
            exit;
        }
    }

    /***
     * 生成菜单
     * @return mixed
     */
    public function createMenu()
    {
        $url = C('url_menu') . HttpUtilController::getAccessToken();
        $jsonMenu = C('menu');
        $resultStr = HttpUtilController::https_request($url, $jsonMenu);
        $obj = json_decode($resultStr);
        if (array_key_exists($obj, 'errcode') && $obj['errcode'] == 0) {
            return $obj->errmsg;
        } else {
            return $obj->errmsg;
        }
    }

    /***
     * 模板推送
     */
    public function sendTemplate()
    {
        $openId = 'oNmrY08K4djd3mAcWsblXPFR5mvI';
        ResponseController::sendTemplateMsg($openId);
    }


}